﻿var errempty = "&nbsp;Giá trị không được để trống.";
var errnegative = "&nbsp;Giá trị nhập lớn hơn 0.";
var errdate = "&nbsp;Nhập đúng định dạng dd-MM-yyyy.";
var errdatetime = "&nbsp;Nhập đúng định dạng dd-MM-yyyy HH:mm.";
var errdatecompare = "&nbsp;Giá trị lớn hơn thời điểm trước";
$(function () {
    $("select").selectpicker({
        style: "btn-flat",
        size: 10
    });
    $("select").on("change", function () {
        $(this).valid();
    });
    $("input:text:not(.input-block-level):first").focus();
    $("input:text:not(.input-block-level), input:submit, .dropdown-toggle:not(.disabled)").bind("keydown", function (e) {
        if (e.which !== 13) return;
        if ($(this).is("input:submit")) {
            $(this).click();
        } else {
            e.preventDefault();
            var n = $("input:text:not(.input-block-level), input:submit, .dropdown-toggle:not(.disabled)").length;
            var nextIndex = $("input:text:not(.input-block-level), input:submit, .dropdown-toggle:not(.disabled)").index(this) + 1;
            if (nextIndex < n) {
                $("input:text:not(.input-block-level), input:submit, .dropdown-toggle:not(.disabled)")[nextIndex].focus();
            }
        }
    });
    $("form").each(function () {
        $(this).validate({
            onfocusout: false,
            invalidHandler: function (form, validator) {
                var errors = validator.numberOfInvalids();
                if (errors) {
                    if ($(validator.errorList[0].element).parent().find("select").length > 0) {
                        $(validator.errorList[0].element).parent().find("div.bootstrap-select > button").focus();
                    } else {
                        validator.errorList[0].element.focus();
                    }
                }
            },
            highlight: function (element) {
                if ($(element).parent().hasClass("input-group")) {
                    $(element).parent().parent().addClass("has-error");
                } else{
                    $(element).parent().addClass("has-error");
                }
            },
            unhighlight: function (element) {
                if ($(element).parent().hasClass("input-group")) {
                    $(element).parent().parent().removeClass("has-error");
                } else {
                    $(element).parent().removeClass("has-error");
                }
            },
            errorPlacement: function (error, element) {
                if ($(element).parent().find("select").length > 0) {
                    error.insertAfter($(element).parent().find("div.bootstrap-select"));
                } else if ($(element).parent().hasClass("input-group")) {
                    error.insertAfter($(element).parent());
                } else {
                    error.insertAfter($(element));
                }
            },
            errorClass: "help-block",
            ignore: ""
        });
    });
    $(document).bind("ajaxSend", function () {
        $("body").modalmanager("loading");
    }).bind("ajaxComplete", function () {
        $("body").modalmanager("removeLoading");
    });
    $(".modal-fullheight").css({
        'height': $(window).height()
    });
    $("input.inputdate").datetimepicker({
        format: "DD-MM-YYYY",
        language: "vi",
        defaultDate: new Date()
    });
    $("input.inputdatetime").datetimepicker({
        format: "DD-MM-YYYY HH:mm",
        language: "vi",
        defaultDate: new Date()
    });
    $(".input-group.inputdate").datetimepicker({
        format: "DD-MM-YYYY",
        language: "vi",
        defaultDate: new Date()
    });
    $(".input-group.inputdatetime").datetimepicker({
        format: "DD-MM-YYYY HH:mm",
        language: "vi",
        defaultDate: new Date()
    });
    $(".numberformat").keypress(function (e) {
        if (e.which !== 8 && e.which !== 0 && (e.which < 48 || e.which > 57)) {
            return false;
        }
        return true;
    });
    $("input.numberpriceright").number(true, 0, ".", ",").css({
        'text-align': "right"
    });
    $("input.numberpriceleft").number(true, 0, ".", ",").css({
        'text-align': "left"
    });
    $.validator.addMethod("dateformat", function (value, element) {
        return this.optional(element) || isDate(value);
    }, errdate);
    $.validator.addMethod("datetimeformat", function (value, element) {
        return this.optional(element) || isDateTime(value);
    }, errdatetime);
    $.validator.addMethod("datecompare", function (value, element, param) {
        return this.optional(element) || (((moment(value, "DD-MM-YYYY") - moment($(param).val(), "DD-MM-YYYY")) / 1000 / 60 / 60 / 24) >= 0);
    }, errdatecompare);
    $.validator.addMethod("number-greater-than-zero", function (value, element) {
        return this.optional(element) || parseFloat(value) > 0;
    }, errnegative);
});

(function ($) {
    $.fn.selectpicker.defaults = {
        noneSelectedText: "Chọn",
        noneResultsText: "Không tìm thấy từ khóa ",
        countSelectedText: function (numSelected, numTotal) {
            return "{0} giá trị được chọn";
        },
        maxOptionsText: function (numAll, numGroup) {
            var arr = [];
            arr[0] = (numAll === 1) ? "Limit reached ({n} item max)" : "Limit reached ({n} items max)";
            arr[1] = (numGroup === 1) ? "Group limit reached ({n} item max)" : "Group limit reached ({n} items max)";
            return arr;
        },
        selectAllText: "Chọn tất cả",
        deselectAllText: "Bỏ chọn",
        multipleSeparator: ", "
    };
    $.fn.modal.defaults.spinner = $.fn.modalmanager.defaults.spinner =
        "<div class=\"loading-spinner\" style=\"width: 200px; margin-left: -100px;\">" +
        "<div class=\"progress progress-striped active\">" +
        "<div class=\"progress-bar\" style=\"width: 100%;\"></div>" +
        "</div>" +
        "</div>";
    $.fn.modal.defaults.maxHeight = function () {
        return $(window).height() - 80;
    };
}(jQuery));

function isDate(txtDate) {
    var currVal = txtDate;
    if (currVal === "") return false;
    var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
    var dtArray = currVal.match(rxDatePattern);
    if (dtArray == null) return false;
    var dtDay = dtArray[1];
    var dtMonth = dtArray[3];
    var dtYear = dtArray[5];
    if (dtMonth < 1 || dtMonth > 12)
        return false;
    else if (dtDay < 1 || dtDay > 31)
        return false;
    else if ((dtMonth === 4 || dtMonth === 6 || dtMonth === 9 || dtMonth === 11) && dtDay === 31)
        return false;
    else if (dtMonth === 2) {
        var isleap = (dtYear % 4 === 0 && (dtYear % 100 !== 0 || dtYear % 400 === 0));
        if (dtDay > 29 || (dtDay === 29 && !isleap))
            return false;
    }
    return true;
}

function isDateTime(txtDate) {
    var currVal = txtDate;
    if (currVal === "") return false;
    var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})(\/|\s)(\d{1,2})(\/|:)(\d{1,2})$/;
    var dtArray = currVal.match(rxDatePattern);
    if (dtArray == null) return false;
    var dtDay = dtArray[1];
    var dtMonth = dtArray[3];
    var dtYear = dtArray[5];
    var dtHours = dtArray[7];
    var dtMinutes = dtArray[9];
    console.log(dtDay + "-" + dtMonth + "-" + dtYear + " " + dtHours + ":" + dtMinutes);
    if (dtMonth < 1 || dtMonth > 12)
        return false;
    else if (dtDay < 1 || dtDay > 31)
        return false;
    else if ((dtMonth === 4 || dtMonth === 6 || dtMonth === 9 || dtMonth === 11) && dtDay === 31)
        return false;
    else if (dtMonth === 2) {
        var isleap = (dtYear % 4 === 0 && (dtYear % 100 !== 0 || dtYear % 400 === 0));
        if (dtDay > 29 || (dtDay === 29 && !isleap))
            return false;
    }
    if (dtHours < 0 || dtHours > 24)
        return false;
    else if (dtMinutes < 0 || dtMinutes > 59) {
        return false;
    }
    return true;
}

function CheckSession() {
    var session = "";
    $.ajax({
        type: "POST",
        url: "/Webservice/wsSelectAll.asmx/CheckSession",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        beforeSend: function () { },
        data: "",
        async: false,
        success: function (n) {
            var data = n.d.split(";");
            session = data[0];
            if (session !== "") {
                setTimeout(function () {
                    window.location.href = "/";
                }, data[1]);
            }
        },
        error: function () { }
    });
    return session;
}